﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Text;

[DefaultProperty("TwitterUsername")]
public partial class Twitter : System.Web.UI.UserControl
{
    #region Enumerations

    public enum Behavior
    {
        LoadAllTweets,
        TimedInterval
    }

    #endregion

    #region Properties

    [Category("Widget Settings")]
    [Description("The username of the Twitter account to display.  Default: Sitefinity")]
    public string TwitterUsername { get; set; }
    
    // Preferences
    [Category("Widget Preferences")]
    [Description("Include a scroll bar if number of tweets is longer than height.")]
    public bool IncludeScrollbar { get; set; }

    [Category("Widget Preferences")]
    [Description("Automatically poll for new results.")]
    public bool PollForNewResults { get; set; }

    [Category("Widget Preferences")]
    [Description("The number of tweets you would like to display. Default: 4")]
    public int NumberOfTweets { get; set; }

    [Category("Widget Preferences")]
    [Description("Begin each tweet with the hashtag of the tweeter.")]
    public bool ShowHashtags { get; set; }

    [Category("Widget Preferences")]
    [Description("Show timestamps for each individual tweet.")]
    public bool ShowTimestamps { get; set; }

    [Category("Widget Preferences")]
    [Description("Show avatars with each individual tweet.")]
    public bool ShowAvatars { get; set; }
    
    // Behavior
    [Category("Widget Behavior")]
    [Description("If Timed Interval is selected for the behavior, than you can set if the results should be looped. ")]
    public bool TimedInterval_LoopResults { get; set; }
    
    [Category("Widget Behavior")]
    [Description("Set the desired behavior.  Default: Load all tweets")]
    public Behavior SetBehavior { get; set; }
    
    [Category("Widget Behavior")]
    [Description("If Timed Interval is selected for the behavior, then you can set the speed at which the tweets will appear on the screen, in seconds.")]
    public int TimedInterval_TweetInterval { get; set; }

    // Appearance
    [Category("Widget Appearance")]
    [Description("Sets the background color of the tweets. Default: #000000")]
    public string TweetBackgroundColor { get; set; }

    [Category("Widget Appearance")]
    [Description("Sets the text color of the widget outer shell. Default: #ffffff")]
    public string ShellTextColor { get; set; }

    [Category("Widget Appearance")]
    [Description("Sets the background color of the widget outer shell. Default: #333333")]
    public string ShellBackgroundColor { get; set; }

    [Category("Widget Appearance")]
    [Description("Sets the color of the links in the tweets. Default: #4aed05")]
    public string LinkColor { get; set; }   
  
    [Category("Widget Appearance")]
    [Description("Sets the text color of the tweets. Default: #ffffff")]
    public string TweetTextColor { get; set; }
    
    // Dimensions
    [Category("Widget Dimensions")]
    [Description("Set the height of the widget. Default: 300")]
    public int Height { get; set; }

    [Category("Widget Dimensions")]
    [Description("Set the width of the widget. Default: 250")]
    public int Width { get; set; }
    
    #endregion

    #region Events

    protected void Page_Load(object sender, EventArgs e)
    {
        ValidateColors();
        
        const string csname = @"TwitterScript";
        var cstype = GetType();
        var cs = Page.ClientScript;

        // Register the widget javascript library.
        if (!cs.IsClientScriptBlockRegistered(cstype, @"TwitterResource")) cs.RegisterClientScriptBlock(cstype, @"TwitterResource", @"<script src='http://widgets.twimg.com/j/2/widget.js'></script>");

        // Build the widget properties script.
        if (cs.IsClientScriptBlockRegistered(cstype, @"TwitterResource"))
        {
            var twitterScript = new StringBuilder();
            twitterScript.Append(@"<script>");
            twitterScript.Append(@"new TWTR.Widget({");
            twitterScript.Append(@"version: 2,");
            twitterScript.Append(@"type: 'profile',");
            
            // Number of Tweets
            twitterScript.Append(@"rpp: " + (NumberOfTweets > 0 ? NumberOfTweets.ToString() : @"4") + @",");
            
            // Behavior - Load all tweets
            twitterScript.Append(@"interval: " + (SetBehavior.Equals(Behavior.TimedInterval) ? (TimedInterval_TweetInterval * 1000).ToString() : @"6000") + @",");

            // Width
            twitterScript.Append(@" width: " + (Width > 0 ? Width.ToString() : @"250") + @",");
            
            // Height
            twitterScript.Append(@"height: " + (Height > 0 ? Height.ToString() : @"300") + @",");
            
            twitterScript.Append(@"theme: {");
            twitterScript.Append(@"shell: {");
            
            // Shell Background color 
            twitterScript.Append(@"background: '" + ShellBackgroundColor + @"',");
            
            // Shell Foreground color
            twitterScript.Append(@"color: '" + ShellTextColor + @"'");
            twitterScript.Append(@"},");
            twitterScript.Append(@"tweets: {");
            
            // Tweet Bckground color
            twitterScript.Append(@"background: '" + TweetBackgroundColor + @"',");
            
            // Tweet Foreground color
            twitterScript.Append(@"color: '" + TweetTextColor + @"',");
            
            // Tweet Link color
            twitterScript.Append(@"links: '" + LinkColor + @"'");
            twitterScript.Append(@"}");
            twitterScript.Append(@"},");
            twitterScript.Append(@"features: {");
            
            // Include scrollbar?
            twitterScript.Append(@"scrollbar: " + IncludeScrollbar.ToString().ToLower() + @",");
            
            // Timed Interval - Loop results?
            twitterScript.Append(@"loop: " + (SetBehavior.Equals(Behavior.TimedInterval) ? TimedInterval_LoopResults.ToString().ToLower() : @"false") + @",");
            
            // Poll for new results?
            twitterScript.Append(@"live: " + PollForNewResults.ToString().ToLower() + @",");
            
            // Show hashtags?
            twitterScript.Append(@"hashtags: " + ShowHashtags.ToString().ToLower() + @",");
            
            // Show Timestamps?
            twitterScript.Append(@"timestamp: " + ShowTimestamps.ToString().ToLower() + @",");
            
            // Show Avatars?
            twitterScript.Append(@"avatars: " + ShowAvatars.ToString().ToLower() + @",");

            // Behavior - Load all tweets
            twitterScript.Append(@"behavior: '" + (SetBehavior.Equals(Behavior.LoadAllTweets) ? @"all" : @"default") + @"'");
            twitterScript.Append(@"}");
            
            // Username
            twitterScript.Append(@"}).render().setUser('" + (String.IsNullOrEmpty(TwitterUsername) ? "sitefinity" : TwitterUsername) + @"').start();");
            
            twitterScript.Append(@"</script>");

            lblTwitter.Text = twitterScript.ToString();
        }
    }

    #endregion

    #region Methods

    private void ValidateColors()
    {
        if (!IsValidColor(ShellBackgroundColor)) ShellBackgroundColor = @"#333333";
        if (!IsValidColor(ShellTextColor)) ShellTextColor = @"#ffffff";
        if (!IsValidColor(TweetBackgroundColor)) TweetBackgroundColor = @"#000000";
        if (!IsValidColor(TweetTextColor)) TweetTextColor = @"#ffffff";
        if (!IsValidColor(LinkColor)) LinkColor = @"#4aed05";
    }

    private static bool IsValidColor(string colorValue)
    {
        try 
        {
            // If it is a color by name.
            if (Color.FromName(colorValue).IsKnownColor)
                return true;
            
            // If it is a color by hex value.
            ColorTranslator.FromHtml(colorValue);

            return true;
        }
        catch
        {
            return false;
        }
    }

    #endregion
}
